<?php
declare(strict_types=1);
/**
 * Create 范钟<coder.zf@outlook.com> 2019/7/27
 */

namespace models;


use think\Collection;
use think\Model;

class Sorts extends Model
{

    protected $table = 'cms_sorts';

    static public function getInstance(int $id): self
    {
        return self::whereRaw('id=?', [$id])->findOrEmpty();
    }

    /**
     * 获取可用菜单
     * @return array
     * @throws
     */
    static public function getMenus(): array
    {
        $menus = self::whereRaw('is_show=1 and state=1')->select();
        $list = self::getList($menus);
        return $list;
    }

    /**
     * 递归分类
     * @param Collection $menus
     * @param int $id
     * @return array
     */
    static private function getList(Collection $menus, int $id = 0): array
    {
        $list = [];
        foreach ($menus as $menu) {
            if ($id == $menu->pid) {
//                $menus = $menus->where('id', 'neq', $menu->id);
                $menu->tree = self::getList($menus, $menu->id);
                $list[] = $menu;
            }
        }
        return $list;
    }

    /**
     * 生成对应的url连接
     * @return mixed|string
     */
    public function getUrl()
    {
        switch ($this->getData('type')) {
            case 0:
                $url = $this->getData('data');
                break;
            case 1:
                $url = url('page/show', ['id' => $this->id]);
                break;
            case 2:
                $url = "javascript:void(0);";
                break;
            case 3:
                $url = url('article/detail', ['id' => $this->id]);
                break;
            case 4:
                $url = url('article/list', ['id' => $this->id]);
                break;
            case 5:
                $url = url('album/list', ['id' => $this->id]);
                break;
            default:
                $url = '/';
        }
        return $url;
    }

}
